package com.store.app.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.bean.EventBusBean;
import com.store.app.imlife.utils.ToastTools;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.pay.alipay.Alipay;
import com.store.app.pay.alipay.AlipayModel;
import com.store.app.pay.alipay.AlipayState;
import com.store.app.utils.MoneyUtil;
import com.store.app.utils.SettingData;
import com.store.app.utils.Utils;
import com.store.app.wxapi.WXOrderbean;
import com.store.app.wxapi.WetchatPay;

import org.json.JSONObject;

import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * 支付确认页面
 */
public class ConfirmPaymentActivity extends BaseActivity implements AlipayState, IOnHttpListener {
    //应付金额
    //title
    private TextView tv_title;
    //提交
    private LinearLayout tv_submit;
    //支付选择
    private RelativeLayout relat1, relat2, relat3;
    //账户余额
    private TextView tv_yuer;
    //支付选择imgview
    private ImageView img1, img2, img3;
    //支付选择 1 余额 2支付宝 3微信
    private int pay_type = 1;
    //支付宝请求订单获取的model
    private AlipayModel model;
    private WXOrderbean wxOrderbean;
    private String dataStr;
    private MyReceiver myReceiver;
    private TextView tv_sum_money;//应付
    private TextView tv_total_price;//合计
    private TextView tv_div_fee;//邮费
    private NetRequest netRequest;
    private String usable_cash_balance = "0";//可用余额

    private String total_fee = "0.00";
    private String pay_info;
    private Map map;                //上个页面返回的支付信息字段
    private String sale_fee = "0.00";//商品费用
    private String delivery_fee = "0.00";//邮费
    private String order_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        sale_fee = getIntent().getStringExtra("sale_fee");
        order_id = getIntent().getStringExtra("order_id");
        delivery_fee = getIntent().getStringExtra("delivery_fee");

        setContentView(R.layout.activity_confirmpayment);
        initView();
        initData();
        initListeners();
        myReceiver = new MyReceiver();
        registerReceiver(myReceiver, new IntentFilter("FINISH"));
        netRequest = new NetRequest(this);
        netRequest.requestUsableCashBalanceFind(1);
        netRequest.requestWypOrderPayFind(6, order_id);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }


    @Override
    public void finish() {
        dismissProgressDialog();
        super.finish();
    }

    private void initListeners() {
        //点击支付
        tv_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                if (pay_type == 1) {
                    if (!MoneyUtil.moneyComp(usable_cash_balance + "", tv_sum_money.getText().toString())) {
                        Toast.makeText(ConfirmPaymentActivity.this, "可用零钱余额不足,请选择其他支付方式！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (map == null) {
                        return;
                    }
                    showConfirmDialog("", "是否确定支付" + tv_sum_money.getText().toString() + "元 ?", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            showProgressDialog("", "支付中...", true);
                            Log.v("zyl", "支付中");

                            netRequest.requestWypOrderPay(3, map, SettingData.PAYMENT_WAY_05);
                        }
                    });

                } else if (pay_type == 2) {
                    if (map == null) {
                        return;
                    }
                    //支付宝的支付方式 ZFFS_01
                    netRequest.requestWypOrderPay(4, map, SettingData.PAYMENT_WAY_01);
                } else if (pay_type == 3) {
                    if (map == null) {
                        return;
                    }
                    boolean ifInstall = Utils.isWXAppInstalledAndSupported(ConfirmPaymentActivity.this);
                    if (ifInstall) {
                        netRequest.requestWypOrderPay(5, map, SettingData.PAYMENT_WAY_02);
                    } else {
                        showToast("尚未安装微信,请检查您的手机");
                        return;
                    }

                }
            }
        });
        findViewById(R.id.public_ll_return).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        relat1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pay_type = 1;
                img1.setBackgroundResource(R.drawable.wyp_pay_circle);
                img2.setBackgroundResource(R.drawable.wyp_pay_circle_gray);
                img3.setBackgroundResource(R.drawable.wyp_pay_circle_gray);

            }
        });
        relat2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pay_type = 2;
                img1.setBackgroundResource(R.drawable.wyp_pay_circle_gray);
                img2.setBackgroundResource(R.drawable.wyp_pay_circle);
                img3.setBackgroundResource(R.drawable.wyp_pay_circle_gray);
            }
        });
        relat3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pay_type = 3;
                img1.setBackgroundResource(R.drawable.wyp_pay_circle_gray);
                img2.setBackgroundResource(R.drawable.wyp_pay_circle_gray);
                img3.setBackgroundResource(R.drawable.wyp_pay_circle);
            }
        });


    }

    private void initData() {

        tv_title.setText("确认支付");
        tv_sum_money.setText(total_fee);//应付
        tv_total_price.setText(sale_fee);//商品费
    }


    private void initView() {
        tv_title = (TextView) findViewById(R.id.tvTitle);
        tv_submit = (LinearLayout) findViewById(R.id.btnPay);
        relat1 = (RelativeLayout) findViewById(R.id.pay_relat1);
        relat2 = (RelativeLayout) findViewById(R.id.pay_relat2);
        relat3 = (RelativeLayout) findViewById(R.id.pay_relat3);
        tv_yuer = (TextView) findViewById(R.id.yuer);
        img1 = (ImageView) findViewById(R.id.pay_check_1);
        img2 = (ImageView) findViewById(R.id.pay_check_2);
        img3 = (ImageView) findViewById(R.id.pay_check_3);
        tv_sum_money = (TextView) findViewById(R.id.all_price);
        tv_total_price = (TextView) findViewById(R.id.allMoney);
        tv_div_fee = (TextView) findViewById(R.id.tv_div_fee);
        tv_total_price.setText(sale_fee);
        tv_div_fee.setText(delivery_fee);
    }

    @Override
    public void onAlipaySuccess() {
        Log.v("zyl", "支付宝支付成功");
        Toast.makeText(ConfirmPaymentActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
        EventBus.getDefault().post(new EventBusBean(206));
        EventBus.getDefault().post(new EventBusBean(207));
        finish();
    }

    @Override
    public void onAlipayFail() {
        Log.v("zyl", "支付宝支付失败");
    }

    @Override
    public void onAfinalFail() {
        dismissProgressDialog();
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        dismissProgressDialog();
        //可用资产
        if (requestId == 1) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                usable_cash_balance = jsonObject.getString("usable_cash_balance");
                Log.v("zyl", "设置可用金额：" + usable_cash_balance);
                tv_yuer.setText("¥ " + usable_cash_balance);
            } catch (Exception e) {
            }
        }
        //查询资产信息
        else if (requestId == 2) {
        }
        //余额支付成功
        else if (requestId == 3) {
            ToastTools.showShort(ConfirmPaymentActivity.this, "余额支付成功");
            //刷新订单页面，并发个通知关闭订单详情页面
            EventBus.getDefault().post(new EventBusBean(206));
            EventBus.getDefault().post(new EventBusBean(207));
            finish();
        }
        //支付宝支付成功（接口调用成功）
        else if (requestId == 4) {
            model = new AlipayModel();
            model.json2Model(result);
            new Alipay(ConfirmPaymentActivity.this, model, ConfirmPaymentActivity.this).pay();
        }
        //微信支付成功（接口调用成功）
        else if (requestId == 5) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                wxOrderbean = new WXOrderbean();
                wxOrderbean.setTransaction_no(jsonObject.getString("transaction_no"));
                wxOrderbean.setTimestamp(jsonObject.getString("timestamp"));
                wxOrderbean.setSign(jsonObject.getString("sign"));
                wxOrderbean.setPartnerid(jsonObject.getString("partnerid"));
                wxOrderbean.setPackageX(jsonObject.getString("package"));
                wxOrderbean.setNoncestr(jsonObject.getString("noncestr"));
                wxOrderbean.setAppid(jsonObject.getString("appid"));
                wxOrderbean.setPrepayid(jsonObject.getString("prepayid"));
                WetchatPay wetchatPay = new WetchatPay(ConfirmPaymentActivity.this, wxOrderbean);
                wetchatPay.pay();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestId == 6) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                JSONObject jsonObject1 = jsonObject.getJSONObject("pay_info");
                pay_info = jsonObject1.toString();
                map = Utils.getMapForJson(pay_info);
                total_fee = map.get("total_fee").toString();
                tv_sum_money.setText(total_fee);//应付
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        dismissProgressDialog();
        ToastTools.showShort(this, msg);
    }

    /**
     * 微信支付成功之后发送一个广播过来关闭页面
     */
    private class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.v("zyl", "接收到广播");
            Toast.makeText(ConfirmPaymentActivity.this, "支付成功", Toast.LENGTH_LONG).show();
            EventBus.getDefault().post(new EventBusBean(206));
            EventBus.getDefault().post(new EventBusBean(207));
            finish();
        }
    }
}
